package com.cskaoyan.utils;

import com.mysql.jdbc.Driver;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {

    static String url = null;
    static String username = null;
    static String password = null;
    static String driverClassName = null;

    static {

//        System.out.println("11111111");

        Properties properties = new Properties();
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("jdbc.properties");
            properties.load(fileInputStream);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
        driverClassName = properties.getProperty("driverClassName");
    }



    // 获取连接
    public static Connection getConnection(){

//        System.out.println("222222");

        Connection connection = null;

        // 注册驱动
        try {
            DriverManager.registerDriver(new Driver());
        } catch (SQLException e) {
            e.printStackTrace();
        }

//        try {
//            Class.forName(driverClassName);
//
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }


        // 获取连接 其实就是建立Java应用程序和数据库之间的连接
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return connection;
    }


    // 关闭资源
    public static void closeResources(Connection connection, Statement statement, ResultSet resultSet){

        try {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }finally {
            try {
                if (statement != null) {
                    try {
                        statement.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }finally {
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }


    }
}
